////////////////////////////////////////////////////////////////////////////////
//  COPYRIGHT (C) 2010 TELECOM DIGITAL MEDIA ("TDMEDIA").
//  ALL RIGHTS RESERVED.
//
//  THIS IS CONFIDENTIAL AND PROPRIETARY INTELLECTUAL PROPERTY OWNED BY AND
//  CREATED ON BEHALF OF TDMEDIA. ANY FORM OF DISTRIBUTION, COPY,
//  MODIFICATION WITHOUT THE WRITTEN CONSENT FROM TDMEDIA IS STRICTLY
//  PROHIBITED.
////////////////////////////////////////////////////////////////////////////////
package cc.telecomdigital.tdstock.activity.groups.foreignexchange;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import cc.telecomdigital.tdstock.CommonDefn;
import cc.telecomdigital.tdstock.DateUtils;
import cc.telecomdigital.tdstock.ITDLApplication;
import cc.telecomdigital.tdstock.R;
import cc.telecomdigital.tdstock.Framework.UniqueItem.TDStockLog;
import cc.telecomdigital.tdstock.Http.H_CODE;
import cc.telecomdigital.tdstock.Http.HttpSuperClassStockBaseActivity;
import cc.telecomdigital.tdstock.Http.Services.HttpAppInfo;
import cc.telecomdigital.tdstock.Http.Services.H_HttpServiceRequest.H_UserClient_HttpRequest_Result;
import cc.telecomdigital.tdstock.Tools.ActivityGroupController;
import cc.telecomdigital.tdstock.activity.groups.ForeignExchangeGroup;
import cc.telecomdigital.tdstock.adapter.ThreeTextColumnHolder;
import cc.telecomdigital.tdstock.adapter.ThreeTextColumnItemAdapter;

/**
 * @author haibo for list item named "Exchange rate of RMB"
 */
public class ExchangeRateRMBActivity extends HttpSuperClassStockBaseActivity
{
	private static final String						TO_HK			= "對港幣";
	private static final String						TO_USD			= "對美元";
	private static final String						TO_EUR			= "歐元";
	private static final String						TO_JPY			= "日元";
	private static final String						TO_GBP			= "英鎊";

	private static final String						HK				= "HKDCNY";
	private static final String						USD				= "USDCNY";
	private static final String						EUR				= "EURCNY";
	private static final String						JPY				= "JPYCNY";
	private static final String						GBP				= "GBPCNY";

	private static final String						TODAY			= "今天";
	private static final String						LAST_WEEK		= "一周前";
	private static final HashMap<String, String>	CODE_TO_NAME	= new HashMap<String, String>();
	static
	{
		CODE_TO_NAME.put(USD, TO_USD);
		CODE_TO_NAME.put(HK, TO_HK);
		CODE_TO_NAME.put(JPY, TO_JPY);
		CODE_TO_NAME.put(GBP, TO_GBP);
		CODE_TO_NAME.put(EUR, TO_EUR);
	}

	protected static final String					TAG				= ExchangeRateRMBActivity.class.getSimpleName();
	private static final long						START_ID		= 90000l;

	private TextView								_topBar;
	private ListView								_listView;
	private Button									_toolBtnReturn;
	private ThreeTextColumnItemAdapter				_adapter;
	private List<ThreeTextColumnHolder>				_list;
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.more_exchange_rate_rmb);

		_toolBtnReturn = (Button) findViewById(R.id.more_returnbtn);
		_toolBtnReturn.setFocusable(true);
		_toolBtnReturn.setClickable(true);
		_toolBtnReturn.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				TDStockLog.d(TAG, "close current activity and forwarding to the previous");

//				Intent intent = new Intent(getApplicationContext(), ForeignExchangeRateOptionsListActivity.class);
//				intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NO_USER_ACTION);
//				SwitchForwardActivity(ForeignExchangeRateOptionsListActivity.class, intent);
				
				SwitchBackActivity();
			}
		});

		_topBar = (TextView) findViewById(R.id.top_bar_title);
		_listView = (ListView) findViewById(R.id.exchange_rate_list);

		_list = new ArrayList<ThreeTextColumnHolder>();

		_adapter = new ThreeTextColumnItemAdapter(LayoutInflater.from(this),
				_list);

		_listView.setAdapter(_adapter);
	}

	@Override
	protected void onResume()
	{
		super.onResume();
		updateTitle();
	}

	private void updateAdapter(List<String[]> list)
	{
		if (list == null)
		{
			return;
		}

		_list.clear();

		{
			ThreeTextColumnHolder holder = new ThreeTextColumnHolder();
			holder.left = new TextView(this);
			holder.right = new TextView(this);
			holder.mid = new TextView(this);
			holder.id = START_ID - 1;
			holder.left.setText("");
			holder.mid.setText(TO_HK);
			holder.right.setText(TO_USD);
			_list.add(holder);
		}

		Date date = new Date();
		// int startMonth = date.getMonth();

		/**
		 * modified by haibo, 2011-10-10, using the first day as today, using
		 * the last day as the last week...
		 */

		Date firstDateAsToday = null;
		Date lastDateAsLastWeekDay = null;

		int count = 0;
		for (int index = 0; index < 20; index++)
		{

			String hkRate = getCurrencyRate(date, HK, list);
			/* if(!TextUtils.isEmpty(hkRate) && count < 5) { */
			if (!TextUtils.isEmpty(hkRate)
					&& /* date.getMonth() == startMonth */count < 5)
			{
				if (firstDateAsToday == null)
				{
					firstDateAsToday = date; // init once.
				}

				lastDateAsLastWeekDay = date; // init 5 times;

				ThreeTextColumnHolder holder = new ThreeTextColumnHolder();
				holder.left = new TextView(this);
				holder.right = new TextView(this);
				holder.mid = new TextView(this);
				holder.id = START_ID + index;
				holder.left.setText(DateUtils.formatDate(date, "MM/dd"));
				holder.mid.setText(hkRate);
				holder.right.setText(getCurrencyRate(date, USD, list));
				_list.add(holder);
				count++;
			}
			date = DateUtils.getDateBefore(date, 1);
		}

		{
			ThreeTextColumnHolder holder = new ThreeTextColumnHolder();
			holder.left = new TextView(this);
			holder.right = new TextView(this);
			holder.mid = new TextView(this);
			holder.id = START_ID + _list.size();
			holder.left.setText("");
			holder.mid.setText(TODAY);
			holder.right.setText(LAST_WEEK);
			_list.add(holder);
		}

		Date today = new Date();
		Date lastWeekDay = /* DateUtils.getDateBefore(today, 6); */lastDateAsLastWeekDay == null ? DateUtils.getDateBefore(today, 6) : lastDateAsLastWeekDay;
		// Date lastWeekDay = DateUtils.getDateBefore(today, 7);
		{
			ThreeTextColumnHolder holder = new ThreeTextColumnHolder();
			holder.left = new TextView(this);
			holder.right = new TextView(this);
			holder.mid = new TextView(this);
			holder.id = START_ID + 10;
			holder.left.setText(TO_EUR);
			holder.mid.setText(getCurrencyRate(/* today */firstDateAsToday == null ? today : firstDateAsToday, EUR, list));
			holder.right.setText(getCurrencyRateEx(lastWeekDay, EUR, list));
			_list.add(holder);
		}
		{
			ThreeTextColumnHolder holder = new ThreeTextColumnHolder();
			holder.left = new TextView(this);
			holder.right = new TextView(this);
			holder.mid = new TextView(this);
			holder.id = START_ID + 11;
			holder.left.setText(TO_JPY);
			holder.mid.setText(getCurrencyRate(/* today */firstDateAsToday == null ? today : firstDateAsToday, JPY, list));
			holder.right.setText(getCurrencyRateEx(lastWeekDay, JPY, list));
			_list.add(holder);
		}

		{
			ThreeTextColumnHolder holder = new ThreeTextColumnHolder();
			holder.left = new TextView(this);
			holder.right = new TextView(this);
			holder.mid = new TextView(this);
			holder.id = START_ID + 12;
			holder.left.setText(TO_GBP);
			holder.mid.setText(getCurrencyRate(/* today */firstDateAsToday == null ? today : firstDateAsToday, GBP, list));
			holder.right.setText(getCurrencyRateEx(lastWeekDay, GBP, list));
			_list.add(holder);
		}

		((ITDLApplication) getApplicationContext()).setObject(null);
		_adapter.notifyDataSetChanged();
	}

	private void updateTitle()
	{
		String title = ((ITDLApplication) getApplicationContext()).getString(CommonDefn.TOP_BAR_TITLE);
		if (_topBar != null && title != null)
			_topBar.setText(title);
	}

	private String getCurrencyRate(Date date, String currencyName,
			List<String[]> list)
	{
		String dateStr = DateUtils.formatDate(date, "yyyy-MM-dd");
		for (String[] array : list)
		{
			if (dateStr.equals(array[2].substring(0, 10))
					&& currencyName.equals(array[0]))
			{
				return array[1];
			}
		}
		return "";
	}

	private String getCurrencyRateEx(Date date, String currencyName,
			List<String[]> list)
	{
		String dateStr = DateUtils.formatDate(date, "yyyy-MM-dd");
		int count = 0;
		while (count < 20)
		{
			for (String[] array : list)
			{
				if (dateStr.equals(array[2].substring(0, 10))
						&& currencyName.equals(array[0]))
				{
					return array[1];
				}
			}
			count++;
			date = DateUtils.getDateBefore(date, 1);
			TDStockLog.d("SystemInfo", "dddddddddddddddd=" + date);
			dateStr = DateUtils.formatDate(date, "yyyy-MM-dd");
		}

		return "";
	}

	@Override
	public ActivityGroupController GetActivityGroupController()
	{
		return ForeignExchangeGroup.GetActivityGroupHostControl();
	}

	@Override
	protected H_CODE GetDataFromHttpServer()
	{
		return HttpAppInfo.SendFXRateRMBRequest(actContext, this);
	}

	@Override
	protected void H_UserClient_HttpRequest_Response_Sub(final H_UserClient_HttpRequest_Result iResult)
	{
		if(!iResult.MStatus.equals("0"))
		{
			ShowMessageDialog(iResult.MError+"("+iResult.MStatus+")");
			return;
		}
	
		Runnable runnable = new Runnable()
		{
			public void run()
			{
				updateAdapter(iResult.contentStores);
			}
		};
		_messageHandler.post(runnable);
	}

}
